﻿using System;
using System.Collections;
using System.Collections.Generic;
using IDAL;
using Model;

namespace BLL
{
    public class DownloadHistoryService
    {
        private static readonly IDownloadHistoryDAL dal = DALFactory.DataAccess.createDownloadHistoryDAL();

        //新增下载历史
        public Hashtable addDownloadHistory(User user, int resourceId)
        {
            Hashtable ht = new Hashtable();
            Resource resource = new ResourceService().getResourceById(resourceId);
            if (resource == null)
            {
                ht.Add("result", "0");
                ht.Add("message", "资源不存在");
                return ht;
            }
            if (isInDownloadhistory(user, resource))
            {
                ht.Add("result", "0");
                ht.Add("message", "下载历史已被记录");
                return ht;
            }
            DownloadHistory downloadHistory = new DownloadHistory()
            {
                user = user,
                resource = resource,
                time = DateTime.Now
            };
            try
            {
                dal.saveDownloadHistory(downloadHistory);
            }
            catch (Exception e)
            {
                ht.Add("result", "0");
                ht.Add("message", e.Message);
                return ht;
            }
            ht.Add("result", "0");
            ht.Add("message", "新增下载历史成功");
            return ht;
        }

        //得到下载历史列表user
        public IList<DownloadHistory> getUserDownloadHistory(int userId)
        {
            return dal.getDownloadHistory(new UserService().getUserById(userId));
        }

        //得到下载历史列表resource
        public IList<DownloadHistory> getResourceDownloadHistory(int resourceId)
        {
            return dal.getDownloadHistory(new ResourceService().getResourceById(resourceId));
        }

        //判断是否已经存在该下载
        public bool isInDownloadhistory(User user, Resource resource)
        {
            return dal.getDownloadHistory(user, resource) == null ? false : true;
        }

    }
}
